/*
 * @Author: yangzonglong
 * @Date: 2021-03-05 12:08:36
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-31 09:47:44
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect, useCallback } from 'react';
import { Picker } from 'antd-mobile';
import { history } from '@library';
import Icon from './icon/Icon';
import RequiredMark from './RequiredMark';
import { sessionStorageKey } from '../config';
// import { history } from './../../../app/routes';

const divStyle = {
  border: '1px solid rgba(35, 37, 40, 0.1)',
  padding: '0 14px',
  fontSize: '14px',
  height: '45px',
  position: 'relative',
  lineHeight: '45px',
};

const iconStyle = {
  position: 'absolute',
  right: '15px',
  fontSize: '14px',
  top: '0',
};

// 获取条件
const getQuery = (screenCondition) => {
  let obj = { $or: [] };
  screenCondition = screenCondition || [];
  screenCondition.forEach((item) => {
    let _temp = {};
    item.dataSource.forEach((ele) => {
      _temp[ele.field] =
        ele.condition !== 'equal'
          ? {
              [ele.condition]: ele.condition === '$ne' || ele.condition === '$like' ? ele.keyword : [ele.keyword],
            }
          : ele.keyword;
    });

    obj.$or.push(_temp);
  });
  return !screenCondition?.length ? {} : { where: obj };
};

const App = (props, ref) => {
  const { disabled, formItemProps, getData, onClick: _onClick, inputProps, onClear } = props;

  const [value, setValue] = useState(undefined);

  const onClick = useCallback(() => {
    if (disabled) return;
    _onClick();
    let data = getData(true);
    let _cache = {};
    for (let k in data) {
      data.hasOwnProperty(k) && (_cache[k] = data[k]);
    }
    let appMain = document.getElementsByClassName('app-main')[0];
    sessionStorage.setItem(sessionStorageKey['lov_cachedata'], JSON.stringify(_cache));
    sessionStorage.setItem(sessionStorageKey['lov_name'], formItemProps.name);
    sessionStorage.setItem(sessionStorageKey['filedShowName'], JSON.stringify(inputProps.filedShowName));
    sessionStorage.setItem(sessionStorageKey['showFieldName'], inputProps.showFieldName);
    sessionStorage.setItem(sessionStorageKey['scrollTop'], appMain.scrollTop);

    const url = inputProps.serviceType === 'APP' ? `/bk/api/${inputProps.serviceModuleCode}/${inputProps.modulesName}/find` : inputProps.modulesUrl;
    const query = JSON.stringify(getQuery(inputProps.screenCondition));
    const fuzzyField = inputProps.showFieldName;

    history.push(`/tableList/table?url=${url}&query=${query}&fuzzyField=${fuzzyField}`);
  }, [
    _onClick,
    disabled,
    formItemProps.name,
    getData,
    inputProps.filedShowName,
    inputProps.modulesName,
    inputProps.modulesUrl,
    inputProps.screenCondition,
    inputProps.serviceModuleCode,
    inputProps.serviceType,
    inputProps.showFieldName,
  ]);

  const _onClear = useCallback(
    (e) => {
      e.stopPropagation();
      if (disabled) return;
      _onClick();
      let appMain = document.getElementsByClassName('app-main')[0];
      setValue(undefined);
      sessionStorage.setItem(sessionStorageKey['showFieldName'], inputProps.showFieldName);
      sessionStorage.setItem(sessionStorageKey['lov_name'], formItemProps.name);
      sessionStorage.setItem(sessionStorageKey['scrollTop'], appMain.scrollTop);
      sessionStorage.setItem(sessionStorageKey['lov_data'], JSON.stringify({ id: 'id' }));
      onClear();
    },
    [_onClick, disabled, formItemProps.name, inputProps.showFieldName, onClear]
  );

  useEffect(() => {
    if (props.initialValue) setValue(props.initialValue);
  }, [props.initialValue]);

  useImperativeHandle(ref, () => ({
    getData: () => value,
  }));

  return (
    <Picker data={[]} disabled cols={1} value={undefined} onOk={setValue}>
      <div className="am-list-item am-input-item am-list-item-middle">
        <div className="am-list-line">
          <div className="am-input-label am-input-label-5">
            {
              <span>
                {formItemProps?.required && <RequiredMark />}
                {formItemProps?.label}
              </span>
            }
          </div>
          <div style={divStyle} onClick={onClick}>
            {value || <span style={{ color: '#bbb' }}>{inputProps?.placeholder || ''}</span>}
            {value ? <Icon onClick={_onClear} icon="&#xe645;" style={{ ...iconStyle, zIndex: 999 }} /> : <Icon icon="&#xe63b;" style={iconStyle} />}
          </div>
        </div>
      </div>
    </Picker>
  );
};

export default forwardRef(App);
